﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace ApriBox.Mvc.UploadHelpers
{
    public static class Name
    {
        // cahnging name if one exist
        public static string ChangeName(string name, string type = "folder")
        {
            string[] sfile = null;
            if (type == "file")
            {
                sfile = name.Split('.');

                StringBuilder strbf = new StringBuilder();

                for (int n = 0; n < sfile.Length - 1; n++)
                {
                    if (n < sfile.Length - 2)
                        strbf.Append(sfile[n] + ".");
                    else strbf.Append(sfile[n]);
                }
                name = strbf.ToString();
            }


            int i = 1;
            int ind = name.Length - 1;
            StringBuilder temp = new StringBuilder();

            if (name[ind] == ')')
            {
                ind--;
                for (; ind >= 0; ind--)
                {

                    if (name[ind] == '(')
                        break;
                    else
                    {
                        if (ind == 0)
                            if (type == "file")
                                return name + "(" + i + ")" + "." + sfile[sfile.Length - 1];
                            else return name + "(" + i + ")";
                    }
                    temp.Append(name[ind]);

                }
                string num = temp.ToString();
                char[] carr = num.ToCharArray();
                Array.Reverse(carr);
                num = new string(carr);

                if (Int32.TryParse(num, out i))
                {
                    i++;
                    if (type == "file")
                        return name.Substring(0, ind) + "(" + i + ")" + "." + sfile[sfile.Length - 1];
                    else return name.Substring(0, ind) + "(" + i + ")";
                }

                if (type == "file")
                    return name + "(" + ++i + ")" + "." + sfile[sfile.Length - 1];
                else return name + "(" + ++i + ")";
            }
            else
            {
                if (type == "file")
                    return name + "(" + i + ")" + "." + sfile[sfile.Length - 1];
                else return name + "(" + i + ")";
            }

        }
    }
}